﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
using NPOI.POIFS.FileSystem;
using NPOI.HPSF;

public partial class ChamCong : System.Web.UI.Page
{
    SqlParameter[] p;
    clsXuLy ex = new clsXuLy();
    string frmName = "frmChamCong";
    static int f_SuDung = 0, f_Them = 0, f_Sua = 0, f_Xoa = 0, f_XemTatCa = 0, f_InBaoCao = 0;
    public string Header = System.Configuration.ConfigurationSettings.AppSettings["Header"].ToString();
    static int PageNumber = 10;
    static int CurrentPage = 1;
    static DataTable dt, dtPrint, dtLich;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Convert.ToString(Session["user"])))
            gstGetMess("Hết phiên làm việc, vui lòng đăng nhập để tiếp tục", "Default.aspx");
        else
        {
            if (!IsPostBack)
            {
                string idnguoidung = Session["IDUser"].ToString();
                string sql = "select SuDung,Them,Sua,Xoa,InBaoCao,XemTatCa from XDAPhanQuyen where IDnguoidung='" + idnguoidung + "' and tag='" + frmName + "'";

                DataTable dt2 = ex.GetData_Text(sql);
                if (dt2.Rows.Count > 0)
                {
                    f_SuDung = int.Parse(dt2.Rows[0]["SuDung"].ToString());
                    f_Them = int.Parse(dt2.Rows[0]["Them"].ToString());
                    f_Sua = int.Parse(dt2.Rows[0]["Sua"].ToString());
                    f_Xoa = int.Parse(dt2.Rows[0]["Xoa"].ToString());
                    f_InBaoCao = int.Parse(dt2.Rows[0]["InBaoCao"].ToString());
                    f_XemTatCa = int.Parse(dt2.Rows[0]["XemTatCa"].ToString());
                }
                if (f_SuDung.Equals(1))
                {
                    CurrentPage = 1;


                    Title = "Thiết lập chấm công | " + Header;

                    

                    for (int i = 1; i <= 12; i++)
                    {
                        dlThang.Items.Add(new ListItem("Tháng " + i.ToString(), i.ToString()));
                        dlThangLoc.Items.Add(new ListItem("Tháng " + i.ToString(), i.ToString()));
                    }
                    dlThang.SelectedValue = DateTime.Now.Month.ToString();
                    dlThangLoc.SelectedValue = DateTime.Now.Month.ToString();

                    int year1 = DateTime.Now.Year - 3;
                    int year2 = DateTime.Now.Year;
                    for (int i = year2; i >= year1; i--)
                    {
                        dlNam.Items.Add(new ListItem("Năm " + i.ToString(), i.ToString()));
                        dlNamLoc.Items.Add(new ListItem("Năm " + i.ToString(), i.ToString()));
                    }
                    dlNam.SelectedValue = year2.ToString();
                    dlNamLoc.SelectedValue = year2.ToString();

                    btnCancel_Click(sender, e);

                    LoadNhanVien(dlNhanVien);
                    LoadChucVu(dlChucVu);
                    LoadBoPhan(dlBoPhan);
                    
                    LoadNhanVien(dlNhanVienLoc);
                    LoadChucVu(dlChucVuLoc);
                    LoadBoPhan(dlBoPhanLoc);
                    txtSoNgayLamViec.Text = GetLastDayOfMonth(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue)).ToString();
                }
                else
                    gstGetMess("Bạn không có quyền xem trang này", "Home.aspx");

            }
        }
    }
    private void gstGetMess(string gstMess, string gstLink)
    {
        if (gstLink == "")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "')", true);
        else
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "');window.location.href='" + gstLink + "'", true);

    }
    void LoadNhanVien(DropDownList dl)
    {
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
        p[1].SqlDbType = SqlDbType.Int;

        dl.Items.Clear();
        dl.DataSource = ex.GetData("sp_TLChamCong_ListNhanVien",p);
        dl.DataBind();
        dl.Items.Insert(0, new ListItem("--Chọn nhân viên--", ""));
        dl.SelectedIndex = 0;
    }
    public int GetLastDayOfMonth(int iMonth, int Year)
    {
        DateTime dtResult = new DateTime(Year, iMonth, 1);
        dtResult = dtResult.AddMonths(1);
        dtResult = dtResult.AddDays(-(dtResult.Day));
        return dtResult.Day;
    }
    void LoadChucVu(DropDownList dlChucVu)
    {
        dlChucVu.Items.Clear();
        dlChucVu.DataSource = ex.GetData("sp_xdachucvu_ListDrop");
        dlChucVu.DataBind();
        dlChucVu.Items.Insert(0, new ListItem("--Chọn chức vụ--", ""));
        dlChucVu.SelectedIndex = 0;
    }
    void LoadBoPhan(DropDownList dlBoPhan)
    {
        dlBoPhan.Items.Clear();
        dlBoPhan.DataSource = ex.GetData("sp_xdabophan_ListDop");
        dlBoPhan.DataBind();
        dlBoPhan.Items.Insert(0, new ListItem("--Chọn bộ phận--", ""));
        dlBoPhan.SelectedIndex = 0;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (f_Them.Equals(1))
        {
            try
            {

                p = new SqlParameter[8];
                p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                p[1] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
                p[1].SqlDbType = SqlDbType.Int;
                p[2] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
                p[2].SqlDbType = SqlDbType.Int;
                p[3] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVien.SelectedValue));
                p[3].SqlDbType = SqlDbType.UniqueIdentifier;
                p[4] = new SqlParameter("@BoPhan", ex.GetGuid(dlBoPhan.SelectedValue));
                p[4].SqlDbType = SqlDbType.UniqueIdentifier;
                p[5] = new SqlParameter("@ChucVu", ex.GetGuid(dlChucVu.SelectedValue));
                p[5].SqlDbType = SqlDbType.UniqueIdentifier;
                p[6] = new SqlParameter("@NgayLamViec", int.Parse(txtSoNgayLamViec.Text.Trim().Replace(",", "").Equals("") ? "0" : txtSoNgayLamViec.Text.Trim()));
                p[6].SqlDbType = SqlDbType.Int;
                p[7] = new SqlParameter("@NgayNghi", txtNgayNghiViec.Text.Trim());
                p[7].SqlDbType = SqlDbType.VarChar;

                
                ex.ExecuteNonQuerry("sp_xdachamcong_Add", p);
                btnCancel_Click(sender, e);
                gstGetMess("Lưu thành công", "");
            }
            catch (Exception ax)
            {
                gstGetMess("Có lỗi trong quá trình lưu, xem trong file log", "");
                ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tThiết lập chấm công\t" + ax.Message);
            }
        }
        else
            gstGetMess("Bạn không có quyền thêm dữ liệu trên trang này", "");
    }
    protected void btncapnhat_Click(object sender, EventArgs e)
    {
        if (f_Sua.Equals(1))
        {
            try
            {

                Guid gID = new Guid(hdID.Value);
                p = new SqlParameter[11];
                p[0] = new SqlParameter("@IDs", gID);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;

                p = new SqlParameter[8];
                p[0] = new SqlParameter("@IDs", gID);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                p[1] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
                p[1].SqlDbType = SqlDbType.Int;
                p[2] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
                p[2].SqlDbType = SqlDbType.Int;
                p[3] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVien.SelectedValue));
                p[3].SqlDbType = SqlDbType.UniqueIdentifier;
                p[4] = new SqlParameter("@BoPhan", ex.GetGuid(dlBoPhan.SelectedValue));
                p[4].SqlDbType = SqlDbType.UniqueIdentifier;
                p[5] = new SqlParameter("@ChucVu", ex.GetGuid(dlChucVu.SelectedValue));
                p[5].SqlDbType = SqlDbType.UniqueIdentifier;
                p[6] = new SqlParameter("@NgayLamViec", int.Parse(txtSoNgayLamViec.Text.Trim().Replace(",", "").Equals("") ? "0" : txtSoNgayLamViec.Text.Trim()));
                p[6].SqlDbType = SqlDbType.Int;
                p[7] = new SqlParameter("@NgayNghi", txtNgayNghiViec.Text.Trim());
                p[7].SqlDbType = SqlDbType.VarChar;


                ex.ExecuteNonQuerry("sp_xdachamcong_Update", p);
                btnCancel_Click(sender, e);
                gstGetMess("Lưu thành công", "");
            }
            catch (Exception ax)
            {
                gstGetMess("Có lỗi trong quá trình lưu, xem trong file log", "");
                ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tThiết lập chấm công\t" + ax.Message);
            }
        }
        else
            gstGetMess("Bạn không có quyền thêm dữ liệu trên trang này", "");
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        dlNhanVien.SelectedIndex = 0;
        dlBoPhan.SelectedIndex = 0;
        dlChucVu.SelectedIndex = 0;
        txtNgayNghiViec.Text = "";

        btnSave.Visible = true;
        btncapnhat.Visible = false;

        dlThang.Enabled = true;
        dlNam.Enabled = true;
        hdID.Value = "";
        btnNext.Visible = true;
        btnPre.Visible = true;
        btnFirst.Visible = true;

        p = new SqlParameter[2];
        p[0] = new SqlParameter("@PageNumber", 1);
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@RowspPage", PageNumber);
        p[1].SqlDbType = SqlDbType.Int;

        GV.DataSource = ex.GetData("sp_xdachamcong_List", p);
        GV.DataBind();
        btnPrint.Visible = false;
        gvLich.Visible = false;
        btnSave.Visible = CheckKhoa2(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue), frmName, Session["user"].ToString());
        //txtSoNgayLamViec.Text = GetLastDayOfMonth(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue)).ToString();
    }
    protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string ID = e.CommandArgument.ToString();
        hdID.Value = ID;
        Guid gID = new Guid(ID);
        p = new SqlParameter[1];
        p[0] = new SqlParameter("@IDs", gID);
        p[0].SqlDbType = SqlDbType.UniqueIdentifier;

        if (e.CommandName.Equals("Select"))
        {
            DataTable dt = ex.GetData("sp_xdachamcong_ListByID", p);
            if (dt.Rows.Count > 0)
            {
                try
                {
                    dlThang.SelectedValue = dt.Rows[0]["Thang"].ToString();
                    dlNam.SelectedValue = dt.Rows[0]["Nam"].ToString();
                    
                    
                    dlBoPhan.SelectedValue = dt.Rows[0]["BoPhan"].ToString();
                    dlChucVu.SelectedValue = dt.Rows[0]["ChucVu"].ToString();
                    txtNgayNghiViec.Text = dt.Rows[0]["NgayNghi"].ToString();
                    txtSoNgayLamViec.Text = dt.Rows[0]["NgayLamViec"].ToString();
                    dlNhanVien.SelectedValue = dt.Rows[0]["NhanVien"].ToString();
                }
                catch (Exception ax)
                {
                    gstGetMess("Có lỗi trong quá trình xem, xem trong file log", "");
                    ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tThiết lập chấm công\t" + ax.Message);
                }

            }
            btncapnhat.Visible = true;
            btnSave.Visible = false;
            btncapnhat.Visible = CheckKhoa2(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue), frmName, Session["user"].ToString());
            if (btncapnhat.Visible == false)
            {
                dlThang.Enabled = false;
                dlNam.Enabled = false;
            }
        }
        else
            if (e.CommandName.Equals("Del"))
            {
                if (f_Xoa.Equals(1))
                {
                    try
                    {
                        ex.ExecuteNonQuerry("sp_xdachamcong_Del", p);
                        btnCancel_Click(sender, e);
                        gstGetMess("Xóa thành công", "");
                    }
                    catch (Exception ax)
                    {
                        ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tThiết lập chấm công\t" + ax.Message);
                        gstGetMess(ax.Message, "");
                    }
                }
                else
                    gstGetMess("Bạn không có quyền xóa dữ liệu trên trang này", "");
            }
    }
    protected void btnFirst_Click(object sender, EventArgs e)
    {
        CurrentPage = 1;
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@PageNumber", 1);
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@RowspPage", PageNumber);
        p[1].SqlDbType = SqlDbType.Int;

        GV.DataSource = ex.GetData("sp_xdachamcong_List", p);
        GV.DataBind();

        btnPre.Enabled = false;
        btnNext.Enabled = true;
        btnFirst.Enabled = false;
    }
    protected void btnPre_Click(object sender, EventArgs e)
    {
        if (CurrentPage > 1)
        {
            CurrentPage--;
            btnPre.Enabled = true;
            btnNext.Enabled = true;
            btnFirst.Enabled = true;

            p = new SqlParameter[2];
            p[0] = new SqlParameter("@PageNumber", CurrentPage);
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@RowspPage", PageNumber);
            p[1].SqlDbType = SqlDbType.Int;

            GV.DataSource = ex.GetData("sp_xdachamcong_List", p);
            GV.DataBind();

        }
        else
        {
            btnFirst.Enabled = false;
            btnPre.Enabled = false;
            btnNext.Enabled = true;
        }
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        CurrentPage++;
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@PageNumber", CurrentPage);
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@RowspPage", PageNumber);
        p[1].SqlDbType = SqlDbType.Int;

        GV.DataSource = ex.GetData("sp_xdachamcong_List", p);
        GV.DataBind();

        if (GV.Rows.Count.Equals(0))
        {
            btnPre.Enabled = true;
            btnNext.Enabled = false;
        }
        else
        {
            btnPre.Enabled = true;
            btnNext.Enabled = true;
        }
        btnFirst.Enabled = true;
    }
    
    protected void btnTimKiem_Click(object sender, EventArgs e)
    {
        if (dlLoaiTimKiem.SelectedIndex.Equals(0))
        {
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;

            GV.DataSource = ex.GetData("sp_xdachamcong_Search", p);
            GV.DataBind();
        }
        else if (dlLoaiTimKiem.SelectedIndex.Equals(1))
        {
            if (dlNhanVienLoc.SelectedIndex.Equals(0))
                gstGetMess("Chọn nhân viên", "");
            else
            {
                p = new SqlParameter[3];
                p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
                p[0].SqlDbType = SqlDbType.Int;
                p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
                p[1].SqlDbType = SqlDbType.Int;
                p[2] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVienLoc.SelectedValue));
                p[2].SqlDbType = SqlDbType.UniqueIdentifier;

                GV.DataSource = ex.GetData("sp_xdachamcong_SearchByNV", p);
                GV.DataBind();
            }
        }
        else if (dlLoaiTimKiem.SelectedIndex.Equals(2))
        {
            if (dlBoPhanLoc.SelectedIndex.Equals(0))
                gstGetMess("Chọn bộ phận", "");
            else
            {
                p = new SqlParameter[3];
                p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
                p[0].SqlDbType = SqlDbType.Int;
                p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
                p[1].SqlDbType = SqlDbType.Int;
                p[2] = new SqlParameter("@BoPhan", ex.GetGuid(dlBoPhanLoc.SelectedValue));
                p[2].SqlDbType = SqlDbType.UniqueIdentifier;

                GV.DataSource = ex.GetData("sp_xdachamcong_SearchByBoPhan", p);
                GV.DataBind();
            }
        }
        else if (dlLoaiTimKiem.SelectedIndex.Equals(3))
        {
            if (dlChucVuLoc.SelectedIndex.Equals(0))
                gstGetMess("Chọn chức vụ", "");
            else
            {
                p = new SqlParameter[3];
                p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
                p[0].SqlDbType = SqlDbType.Int;
                p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
                p[1].SqlDbType = SqlDbType.Int;
                p[2] = new SqlParameter("@ChucVu", ex.GetGuid(dlChucVuLoc.SelectedValue));
                p[2].SqlDbType = SqlDbType.UniqueIdentifier;

                GV.DataSource = ex.GetData("sp_xdachamcong_SearchByChucVu", p);
                GV.DataBind();
            }
        }
        btnPre.Visible = false;
        btnNext.Visible = false;
        btnFirst.Visible = false;

        btnLich.Visible = GV.Rows.Count > 0;
        gvLich.DataBind();
        gvLich.Visible = false;
        btnPrint.Visible = false;
    }
    protected void dlThang_SelectedIndexChanged(object sender, EventArgs e)
    {
        int songay = GetLastDayOfMonth(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue));
        if (txtNgayNghiViec.Text.Trim().Replace(",", "").Equals(""))
        {
            txtSoNgayLamViec.Text = songay.ToString();
        }
        else
        {
            int n = txtNgayNghiViec.Text.Trim().Split(',').Length;
            txtSoNgayLamViec.Text = (songay - n).ToString();
        }
        if (hdID.Value.Equals(""))
            btnSave.Visible = CheckKhoa2(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue), frmName, Session["user"].ToString());
        else
            btncapnhat.Visible = CheckKhoa2(int.Parse(dlThang.SelectedValue), int.Parse(dlNam.SelectedValue), frmName, Session["user"].ToString());

        LoadNhanVien(dlNhanVien);
    }
    private bool CheckKhoa2(int thang, int nam, string name, string nhanvien)
    {
        p = new SqlParameter[4];
        p[0] = new SqlParameter("@Name", name);
        p[0].SqlDbType = SqlDbType.NVarChar;
        p[1] = new SqlParameter("@Thang", int.Parse(dlThang.SelectedValue));
        p[1].SqlDbType = SqlDbType.Int;
        p[2] = new SqlParameter("@NhanVien", nhanvien);
        p[2].SqlDbType = SqlDbType.NVarChar;
        p[3] = new SqlParameter("@Nam", int.Parse(dlNam.SelectedValue));
        p[3].SqlDbType = SqlDbType.Int;

        string index = ex.GetValueString("sp_KhoaMo_CheckThang", p);

        if (index.Trim().Equals("2"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    protected void dlNhanVien_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (dlNhanVien.SelectedIndex > 0)
            {
                p = new SqlParameter[1];
                p[0] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVien.SelectedValue));
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;

                DataTable d = ex.GetData("sp_xdachamcong_LoadBPCBByNV", p);
                if (d.Rows.Count > 0)
                {
                    dlBoPhan.SelectedValue = d.Rows[0][0].ToString(); //"86ABBA19-7379-4375-B2E9-E846FB77EDE0";
                    dlChucVu.SelectedValue = d.Rows[0][1].ToString(); ;// "DB159662-B8D3-48ED-BD4C-F3AB4967C95B";
                }
            }
            else
            {
                dlBoPhan.SelectedIndex = 0;
                dlChucVu.SelectedIndex = 0;
            }
        }
        catch(Exception ax)
        {
            dlBoPhan.SelectedIndex = 0;
            dlChucVu.SelectedIndex = 0;
        }
    }
    protected void dlLoaiTimKiem_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (dlLoaiTimKiem.SelectedIndex.Equals(0))
        {
            dlChucVuLoc.Visible = false;
            dlBoPhanLoc.Visible = false;
            dlNhanVienLoc.Visible = false;
        }
        else
            if (dlLoaiTimKiem.SelectedIndex.Equals(1))
            {
                dlChucVuLoc.Visible = false;
                dlBoPhanLoc.Visible = false;
                dlNhanVienLoc.Visible = true;
            }
            else if (dlLoaiTimKiem.SelectedIndex.Equals(2))
            {
                dlChucVuLoc.Visible = false;
                dlBoPhanLoc.Visible = true;
                dlNhanVienLoc.Visible = false;
            }
            else if (dlLoaiTimKiem.SelectedIndex.Equals(3))
            {
                dlChucVuLoc.Visible = true;
                dlBoPhanLoc.Visible = false;
                dlNhanVienLoc.Visible = false;
            }
    }
    protected void btnLich_Click(object sender, EventArgs e)
    {
        dtLich = new DataTable();
        int month = GetLastDayOfMonth(int.Parse(dlThangLoc.SelectedValue), int.Parse(dlNamLoc.SelectedValue));
        dtLich.Columns.Add("Nhân viên", typeof(string));
        dtLich.Columns.Add("Bộ phận", typeof(string));
        for (int i = 1; i <= month; i++)
        {
            dtLich.Columns.Add(i.ToString(), typeof(string));
        }
        dtLich.Columns.Add("Tổng ngày làm", typeof(string));

        if (dlLoaiTimKiem.SelectedIndex.Equals(0))
        {
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            dtPrint = ex.GetData("sp_xdachamcong_ChamCong", p);
        }
        else if (dlLoaiTimKiem.SelectedIndex.Equals(1))
        {
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            p[2] = new SqlParameter("@NhanVien", ex.GetGuid(dlNhanVienLoc.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            dtPrint = ex.GetData("sp_xdachamcong_ChamCongByNhanVien", p);
        }
        else if (dlLoaiTimKiem.SelectedIndex.Equals(2))
        {
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            p[2] = new SqlParameter("@BoPhan", ex.GetGuid(dlBoPhanLoc.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            dtPrint = ex.GetData("sp_xdachamcong_ChamCongByBoPhan", p);
        }
        else if (dlLoaiTimKiem.SelectedIndex.Equals(3))
        {
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@Thang", int.Parse(dlThangLoc.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(dlNamLoc.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            p[2] = new SqlParameter("@ChucVu", ex.GetGuid(dlChucVuLoc.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            dtPrint = ex.GetData("sp_xdachamcong_ChamCongByChucVu", p);
        }
        if (dtPrint.Rows.Count > 0)
        {
            int y = 1;
            string[] nn = new string[] {};
            string ngaynghi = "";
            for (int k = 0; k < dtPrint.Rows.Count; k++)
            {
                DataRow dr = dtLich.NewRow();
                y = 1;
                dr[0] = dtPrint.Rows[k]["NhanVien"].ToString();
                dr[1] = dtPrint.Rows[k]["BoPhan"].ToString();
                ngaynghi = dtPrint.Rows[k]["NgayNghi"].ToString().Trim();
                if (ngaynghi.Contains(","))
                {
                    nn = dtPrint.Rows[k]["NgayNghi"].ToString().Split(',');
                    for (int i = 1; i <= month; i++)
                    {
                        y++;
                        if (nn.Contains((i.ToString())))
                            dr[y] = "";
                        else dr[y] = "X";
                    }
                }
                else
                {
                    for (int i = 1; i <= month; i++)
                    {
                        y++;
                        if (ngaynghi.Equals((i.ToString())))
                            dr[y] = "";
                        else dr[y] = "X";
                    }
                }
                dr[y + 1] = dtPrint.Rows[k]["NgayLamViec"].ToString();

                dtLich.Rows.Add(dr);
            }
        }

        
        gvLich.DataSource = dtLich;
        gvLich.DataBind();
        gvLich.Visible = true;
        if (dtPrint.Rows.Count > 0)
        {
            for (int m = 0; m < gvLich.Rows.Count; m++)
            {
                gvLich.Rows[m].Cells[0].HorizontalAlign = HorizontalAlign.Left;
                gvLich.Rows[m].Cells[1].HorizontalAlign = HorizontalAlign.Left;

            }
            btnPrint.Visible = true;
        }
        else btnPrint.Visible = false;
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        PrintNPOI(dtLich);
    }
    void PrintNPOI(DataTable dt)
    {
        var workbook = new HSSFWorkbook();

        if (dt.Rows.Count > 0)
        {
            string sheetname = "Bảng chấm công - "+dlThang.SelectedValue+"-"+dlNam.SelectedValue;

            
            var sheet = workbook.CreateSheet(sheetname);

            #region CSS
            var headerLabelCellStyle = workbook.CreateCellStyle();
            headerLabelCellStyle.Alignment = HorizontalAlignment.LEFT;
            headerLabelCellStyle.BorderBottom = CellBorderType.THIN;
            headerLabelCellStyle.BorderLeft = CellBorderType.THIN;
            headerLabelCellStyle.BorderRight = CellBorderType.THIN;
            headerLabelCellStyle.BorderTop = CellBorderType.THIN;

            var headerLabelFont = workbook.CreateFont();
            headerLabelFont.FontName = "Times New Roman";

            headerLabelFont.FontHeightInPoints = 11;
            headerLabelFont.Color = HSSFColor.BLACK.index;
            headerLabelCellStyle.SetFont(headerLabelFont);

            //--------------------------

            var hsRight = workbook.CreateCellStyle();
            hsRight.Alignment = HorizontalAlignment.RIGHT;
            hsRight.BorderBottom = CellBorderType.THIN;
            hsRight.BorderLeft = CellBorderType.THIN;
            hsRight.BorderRight = CellBorderType.THIN;
            hsRight.BorderTop = CellBorderType.THIN;

            hsRight.SetFont(headerLabelFont);
            //-------------------
            var hsCenter = workbook.CreateCellStyle();
            hsCenter.Alignment = HorizontalAlignment.CENTER;
            hsCenter.BorderBottom = CellBorderType.THIN;
            hsCenter.BorderLeft = CellBorderType.THIN;
            hsCenter.BorderRight = CellBorderType.THIN;
            hsCenter.BorderTop = CellBorderType.THIN;

            hsCenter.SetFont(headerLabelFont);
            //-----------------------

            var hs1 = workbook.CreateCellStyle();
            hs1.Alignment = HorizontalAlignment.LEFT;

            var hsb = workbook.CreateFont();
            hsb.Boldweight = (short)FontBoldWeight.BOLD;
            hsb.FontName = "Times New Roman";

            hsb.FontHeightInPoints = 11;
            hsb.Color = HSSFColor.BLACK.index;
            hs1.SetFont(hsb);

            //-------------
            var hs2 = workbook.CreateCellStyle();
            hs2.Alignment = HorizontalAlignment.CENTER;

            var hsb2 = workbook.CreateFont();
            hsb2.Boldweight = (short)FontBoldWeight.BOLD;
            hsb2.FontName = "Times New Roman";

            hsb2.FontHeightInPoints = 18;
            hsb2.Color = HSSFColor.BLACK.index;
            hs2.SetFont(hsb2);
            //------------------------------
            var hs3 = workbook.CreateCellStyle();
            hs3.Alignment = HorizontalAlignment.CENTER;
            //hs3.BorderBottom = CellBorderType.THIN;
            var hsb3 = workbook.CreateFont();
            hsb3.Boldweight = (short)FontBoldWeight.BOLD;
            hsb3.FontName = "Times New Roman";

            hsb3.FontHeightInPoints = 14;
            hsb3.Color = HSSFColor.BLACK.index;
            hs3.SetFont(hsb3);

            //----------------------------
            var hs4 = workbook.CreateCellStyle();
            hs4.Alignment = HorizontalAlignment.CENTER;
            hs4.BorderBottom = CellBorderType.THIN;
            hs4.BorderLeft = CellBorderType.THIN;
            hs4.BorderRight = CellBorderType.THIN;
            hs4.BorderTop = CellBorderType.THIN;

            var hsb4 = workbook.CreateFont();
            hsb4.Boldweight = (short)FontBoldWeight.BOLD;
            hsb4.FontName = "Times New Roman";

            hsb4.FontHeightInPoints = 11;
            hsb4.Color = HSSFColor.BLACK.index;
            hs4.SetFont(hsb4);

            #endregion

            //Start header-----------------------------------------------------------------------
            #region Header
            //tao hnag dau tien
            var rowIndex = 0;

            //cong ty
            var row = sheet.CreateRow(rowIndex);
            Cell r1c1 = row.CreateCell(0);
            r1c1.SetCellValue("Công ty cổ phần Xây Dựng Đức Anh");
            r1c1.CellStyle = hs1;
            r1c1.Row.Height = 400;

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 4);
            sheet.AddMergedRegion(cra);

            //chi nhanh
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
            r1c1 = row.CreateCell(0);
            r1c1.SetCellValue("Chi nhánh Trạm trộn Lâm Thao");
            r1c1.CellStyle = hs1;
            r1c1.Row.Height = 400;

            cra = new CellRangeAddress(1, 1, 0, 4);
            sheet.AddMergedRegion(cra);

            //tieu de bao cao
            string ngaythang = dlThang.SelectedItem.Text.ToUpper() + " " + dlNam.SelectedItem.Text.ToUpper();
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
            r1c1 = row.CreateCell(0);
            r1c1.SetCellValue("BẢNG CHẤM CÔNG " + ngaythang);
            r1c1.CellStyle = hs2;
            r1c1.Row.Height = 500;

            cra = new CellRangeAddress(2, 2, 0, dt.Columns.Count+1);
            sheet.AddMergedRegion(cra);

            rowIndex++;
            //freeze panes
            sheet.CreateFreezePane(0, 6);
            #endregion
            //End header-----------------------------------------------------------------------

            #region Header1-2
            rowIndex++;
            
            //header2
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
            var cell = row.CreateCell(0);
            cell.SetCellValue("STT");
            cell.CellStyle = hs4;
            cell.Row.Height = 400;

            for(int i=0; i<dt.Columns.Count;i++)
            {
                cell = row.CreateCell(i+1);
                cell.SetCellValue(HttpUtility.HtmlDecode(dt.Columns[i].ToString()));
                cell.CellStyle = hs4;
                cell.Row.Height = 400;
            }
            
            #endregion

            //ghi du lieu tung dong
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                rowIndex++;
                row = sheet.CreateRow(rowIndex);

                cell = row.CreateCell(0);
                cell.SetCellValue((i+1).ToString());
                cell.CellStyle = hs4;
                cell.Row.Height = 400;

                for (int j = 1; j <= dt.Columns.Count; j++)
                {
                    cell = row.CreateCell(j);
                    cell.SetCellValue(HttpUtility.HtmlDecode(dt.Rows[i][j-1].ToString()));
                    
                    if (j >2)
                            cell.CellStyle = hsCenter;
                        else
                            cell.CellStyle = headerLabelCellStyle;
                    cell.Row.Height = 500;
                }

            }
            for (int ih = 0; ih <= dt.Columns.Count; ih++)
            {
                sheet.AutoSizeColumn(ih);
            }

            //end sheet tong hop--------------------------
            using (var exportData = new MemoryStream())
            {
                workbook.Write(exportData);
                string saveAsFileName = "Bảng chấm công-"+dlThang.SelectedItem.Text+" "+dlNam.SelectedItem.Text+".xls";

                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
                Response.Clear();
                Response.BinaryWrite(exportData.GetBuffer());
                Response.End();
            }
        }

    }
}